#include "StdAfx.h"
#include "IDeskTopShare.h"
#include <string>
#include "GetScreen.h"
#include "Jpeg2RgbScreen.h"

//////////////////////////////////////////////////////////////////.
BOOL APIENTRY DllMain( HMODULE hModule,
					  DWORD  ul_reason_for_call,
					  LPVOID lpReserved
					  )
{
	return TRUE;
}


void IDeskTopShare::start(ScreenHeader screenHeader,INCOMMINGDATA callback)
{
	Rgb2JpegScreen lpImage;
	while (TRUE)
	{			
		LPSTR lpData = NULL;
		lpImage.Init(screenHeader.rcArea,screenHeader.nArea);
		lpData = (LPSTR)lpImage.GetScreeenData(screenHeader);
		std::string senddata = std::string((char*)&screenHeader,sizeof(ScreenHeader));
		senddata += std::string((char*)lpData,screenHeader.dwFileSize);
		callback(screenHeader,(char*)senddata.c_str(),(int)senddata.length());
		if (lpData){
			GlobalFree(lpData);
		}
		/**sleep a moment*/
		Sleep(screenHeader.nDelay);
	}
}
DeskTopClient::DeskTopClient(HWND hWnd):
pImg(NULL)
{
	/**init Jpeg2RgbScreen*/
	Jpeg2RgbScreen * m_Jpeg2RgbScreen = new Jpeg2RgbScreen;
	m_Jpeg2RgbScreen->Init(m_hWnd);
	if (m_Jpeg2RgbScreen) pImg = m_Jpeg2RgbScreen;
}

DeskTopClient::~DeskTopClient(void)
{
	/**free Jpeg2RgbScreen*/
	Jpeg2RgbScreen * p = (Jpeg2RgbScreen *)pImg;
	if(p){
		delete p;
		p= NULL;
	}

}
void DeskTopClient::Set_BackGroud_Image(char* img,int size)
{
	if(!img) return;
	std::string data = std::string(img,size);
	/**get ScreenHeader struct*/
	ScreenHeader h;
	memset(&h,0,sizeof(ScreenHeader));
	memcpy(&h,(char*)data.c_str(),sizeof(ScreenHeader));
	data.erase(sizeof(ScreenHeader));
	if(h.dwFileSize<= 0 ) return;
	/**get screen image data*/
	char * lpData  = (char *)GlobalAlloc(GMEM_FIXED,h.dwFileSize +1);
	memset(lpData,0,h.dwFileSize +1);
	memcpy(lpData,(char*)data.c_str(),h.dwFileSize);
	Jpeg2RgbScreen * Jpeg = (Jpeg2RgbScreen*)pImg;
	if(!Jpeg) return;
	/**set screen data to Jpeg2RgbScreen*/
	Jpeg->SetScreenData(h,(BYTE *)lpData);
	/**draw the image on the window*/
	Jpeg->Set_BackGroud_Image();
	if (lpData){
		GlobalFree(lpData);
	}
}
///////////////////////////////////////////////////////////////.
__declspec(dllexport) IDeskTopShare * createIDeskTopShare()
{
	IDeskTopShare * p = new IDeskTopShare;
	if(p){
		return p;
	}
	return NULL;
}
__declspec(dllexport) void destroyIDeskTopShare(IDeskTopShare * deskTop)
{
	if(deskTop) delete deskTop;

}
__declspec(dllexport) DeskTopClient * createDeskTopClient(HWND hWnd)
{
	DeskTopClient * p = new DeskTopClient(hWnd);
	if(p){
		return p;
	}
	return NULL;
}
__declspec(dllexport) void destroyDeskTopClient(DeskTopClient * c)
{
   if(c) delete c;
}